package tools;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;

public class ImageCropDialog extends JDialog {
    private BufferedImage originalImage;
    private BufferedImage croppedImage;
    private JLabel imageLabel;
    private Rectangle cropRect = new Rectangle(0, 0, 180, 210); // 初始裁剪区域（适配头像显示尺寸）
    private Point startDrag;

    public ImageCropDialog(Frame parent, BufferedImage image) {
        super(parent, "裁剪头像", true);
        this.originalImage = image;

        // 缩放原图到适合预览的尺寸（保持宽高比）
        int maxWidth = 300, maxHeight = 300;
        double scale = Math.min((double) maxWidth / image.getWidth(), (double) maxHeight / image.getHeight());
        int scaledWidth = (int) (image.getWidth() * scale);
        int scaledHeight = (int) (image.getHeight() * scale);
        BufferedImage scaledImage = new BufferedImage(scaledWidth, scaledHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = scaledImage.createGraphics();
        g2.drawImage(image, 0, 0, 180, 210, null);
        //g2.drawImage(image, 0, 0, scaledWidth, scaledHeight, null);
        g2.dispose();

        imageLabel = new JLabel(new ImageIcon(scaledImage));
        JScrollPane scrollPane = new JScrollPane(imageLabel);
        getContentPane().add(scrollPane, BorderLayout.CENTER);

        // 鼠标事件：绘制裁剪框、支持拖动/调整大小
        imageLabel.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                startDrag = e.getPoint();
                if (cropRect.contains(startDrag)) {
                    // 点击在裁剪框内，准备拖动
                } else {
                    // 点击在裁剪框外，重置裁剪框位置
                    cropRect.setLocation(startDrag);
                }
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                updateCropRect(e);
                repaint();
            }
        });

        imageLabel.addMouseMotionListener(new MouseAdapter() {
            @Override
            public void mouseDragged(MouseEvent e) {
                updateCropRect(e);
                repaint();
            }
        });

        // 底部按钮：确认裁剪、取消
        JPanel btnPanel = new JPanel();
        JButton cropBtn = new JButton("确认裁剪");
        cropBtn.addActionListener(e -> {
            // 计算实际裁剪区域（基于原图比例）
            double xScale = (double) originalImage.getWidth() / scaledImage.getWidth();
            double yScale = (double) originalImage.getHeight() / scaledImage.getHeight();
            int realX = (int) (cropRect.x * xScale);
            int realY = (int) (cropRect.y * yScale);
            int realWidth = (int) (cropRect.width * xScale);
            int realHeight = (int) (cropRect.height * yScale);


            croppedImage = originalImage.getSubimage(realX, realY, realWidth, realHeight);
            croppedImage = scaleImage(croppedImage, 180, 210); // 强制缩放到显示尺寸
            setVisible(false);
        });

        JButton cancelBtn = new JButton("取消");
        cancelBtn.addActionListener(e -> setVisible(false));

        btnPanel.add(cropBtn);
        btnPanel.add(cancelBtn);
        getContentPane().add(btnPanel, BorderLayout.SOUTH);

        pack();
        setLocationRelativeTo(parent);
    }

    // 更新裁剪框大小/位置
    private void updateCropRect(MouseEvent e) {
        if (startDrag == null) return;
        int x = Math.min(startDrag.x, e.getX());
        int y = Math.min(startDrag.y, e.getY());
        int width = Math.abs(e.getX() - startDrag.x);
        int height = Math.abs(e.getY() - startDrag.y);
        cropRect.setBounds(x, y, width, height);
    }

    // 绘制裁剪框（调试用，实际可通过重写 paint 实现更美观的框）
    @Override
    public void paint(Graphics g) {
        super.paint(g);
        Graphics2D g2 = (Graphics2D) g.create();
        g2.setColor(Color.RED);
        g2.setStroke(new BasicStroke(2));
        g2.drawRect(cropRect.x, cropRect.y, cropRect.width, cropRect.height);
        g2.dispose();
    }

    // 获取裁剪后的图像
    public BufferedImage getCroppedImage() {
        return croppedImage;
    }

    // 缩放图像到固定尺寸
    private BufferedImage scaleImage(BufferedImage image, int width, int height) {
        BufferedImage scaled = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = scaled.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2.drawImage(image, 0, 0, width, height, null);
        g2.dispose();
        return scaled;
    }
}